<template>
  <el-form :model="form" :rules="rules" :hide-required-asterisk="true" ref="form" label-position="left" style="width:700px;margin: 0 auto;">
    <el-form-item :label="$t('对象名称')" :label-width="formLabelWidth" prop="name" @input="updateView($event)">
      <el-input id="service-edit-name" v-emoji size='small' v-model="form.name" autocomplete="off" ref="name" key="name"></el-input>
    </el-form-item>
    <el-form-item :label="$t('描述')" :label-width="formLabelWidth" @input="updateView($event)">
      <el-input id="service-edit-desc" v-emoji type="textarea" @keydown.native="handleKeyCode($event)" ref="desc" key="desc" :autosize="{ minRows: 3, maxRows: 5}" :placeholder="$t('请输入内容')" v-model="form.desc">
      </el-input>
    </el-form-item>
    <el-form-item :label="$t('协议')" :label-width="formLabelWidth" prop="cmd_type" @input="updateView($event)" key="cmd_type">
      <el-select v-model="form.cmd_type" size='small' filterable @change="cmdTypeChange" style="width:100%;">
        <el-option :id="`service-edit-desc-${item}`" v-for="(item, index) in cmdTypeList" :key="item" :label="index" :value="item">
        </el-option>
      </el-select>
    </el-form-item>

    <!-- 类型页面-->
    <!-- TCP和UDP -->
    <div v-if="form.cmd_type === '2' || form.cmd_type === '3' || form.cmd_type === '4' || form.cmd_type === '5'">
      <el-form-item :label="$t('端口范围')" prop="ports" :label-width="formLabelWidth" @input="updateView($event)">
        <el-input id="service-edit-ports" v-emoji v-model="form.ports" size='small' ref="ports" key="ports" type="textarea" @keydown.native="handleKeyCode($event)" :autosize="{ minRows: 3, maxRows: 5}" :placeholder="$t('可输入以,分割的多个散列端口或以-连接的端口范围，例如：1,3,5-7')">
        </el-input>
      </el-form-item>
    </div>
    <!-- ICMP -->
    <div v-if="['1'].includes(form.cmd_type)">
      <el-form-item :label="$t('类型')" :label-width="formLabelWidth" prop="type" @input="updateView($event)" key="type">
        <el-input id="service-edit-type" v-emoji size='small' v-model="form.type" ref="type" key="type" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item :label="$t('编码')" :label-width="formLabelWidth" prop="code" @input="updateView($event)" key="code">
        <el-input id="service-edit-code" v-emoji size='small' v-model="form.code" ref="code" key="code" autocomplete="off"></el-input>
      </el-form-item>
    </div>
    <!-- ICMPv6 -->
    <div v-if="['7'].includes(form.cmd_type)">
      <el-form-item label="ICMPv6" :label-width="formLabelWidth" prop="pattern" @input="updateView($event)" v-if="form.cmd_type === '7'" key="nameCmdType">
        <el-select v-model="form.pattern" size='small' filterable @change="nameChange" style="width:100%;">
          <el-option :id="`service-edit-${index}`" v-for="(item,index) in icmpv6ListShow" :key="item" :label="patternShow[item] || item" :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型" :label-width="formLabelWidth" prop="v6Type" @input="updateView($event)" key="v6Type">
        <el-input id="service-edit-v6Type" v-emoji size='small' v-model="form.v6Type" autocomplete="off" :disabled='serviceIcmpv6Status'></el-input>
      </el-form-item>
      <el-form-item label="编码" :label-width="formLabelWidth" prop="v6Code" @input="updateView($event)" key="v6Code">
        <el-input id="service-edit-v6Code" v-emoji size='small' v-model="form.v6Code" autocomplete="off" :disabled='serviceIcmpv6Status'></el-input>
      </el-form-item>
    </div>
    <!-- 其他IP协议 -->
    <div v-if="form.cmd_type === '6'">
      <el-form-item :label="$t('协议号')" :label-width="formLabelWidth" prop="prot" @input="updateView($event)">
        <el-input id="service-edit-prot" v-emoji size='small' v-model="form.prot" ref="prot" key="prot" autocomplete="off"></el-input>
      </el-form-item>
    </div>

  </el-form>

</template>

<script>
import { getServiceIcmpv6 } from '@/api/list/server'
import { inputClass, texttextClass } from '@/utils/input-class.js'
export default {
  inject: ['reload'],
  props: [
    'type_info'
  ],
  name: 'AddrGroupEdit',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入对象名称')))
      } else {
        callback()
      }
    }
    var validatePorts = (rule, value, callback) => {
      let zhStr = /[^\u4E00-\u9FA5]/g
      let msg = ''
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入端口范围')))
      } else {
        let spValue = String(value).split(',')
        for (let item of spValue) {
          if (item.indexOf('-') > -1) {
            let spItem = item.split('-')
            for (let spVa of spItem) {
              msg = this.rulePost(spVa, zhStr) || msg
            }
          } else {
            msg = this.rulePost(item, zhStr) || msg
          }
        }
        if (msg) {
          callback(new Error(msg))
        } else {
          callback()
        }
      }
    }
    var validateType = (rule, value, callback) => {
      let zhStr = /[^\u4E00-\u9FA5]/g
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入ICMP类型')))
      } else if (!String(value).match(zhStr) || (String(value).match(zhStr).length !== String(value).length)) {
        callback(new Error(this.$t('不能输入中文')))
      } else {
        callback()
      }
    }
    var validateCode = (rule, value, callback) => {
      let zhStr = /[^\u4E00-\u9FA5]/g
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入ICMP编码')))
      } else if (!String(value).match(zhStr) || (String(value).match(zhStr).length !== String(value).length)) {
        callback(new Error(this.$t('不能输入中文')))
      } else {
        callback()
      }
    }
    var validateV6Type = (rule, value, callback) => {
      let zhStr = /[^\u4E00-\u9FA5]/g
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入ICMPv6类型')))
      } else if (!String(value).match(zhStr) || (String(value).match(zhStr).length !== String(value).length)) {
        callback(new Error(this.$t('不能输入中文')))
      } else {
        callback()
      }
    }
    var validateV6Code = (rule, value, callback) => {
      let zhStr = /[^\u4E00-\u9FA5]/g
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入ICMPv6编码')))
      } else if (!String(value).match(zhStr) || (String(value).match(zhStr).length !== String(value).length)) {
        callback(new Error('不能输入中文'))
      } else {
        callback()
      }
    }
    var validateProt = (rule, value, callback) => {
      let zhStr = /[^\u4E00-\u9FA5]/g
      if (!String(value).trim()) {
        callback(new Error(this.$t(this.$t('请输入协议号'))))
      } else if (!String(value).match(zhStr) || (String(value).match(zhStr).length !== String(value).length)) {
        callback(new Error(this.$t(this.$t('不能输入中文'))))
      } else {
        callback()
      }
    }
    return {
      icmpv6List: {},
      serviceIcmpv6Status: false,
      icmpv6ListShow: [],
      form: {
        cmd_type: '2',
        pattern: 'default',
        name: '',
        desc: '',
        ports: '',
        type: '',
        v6Type: '',
        code: '',
        v6Code: '',
        prot: ''
      },
      patternShow: {'default': this.$t('用户自定义')},
      cmdTypeList: {
        'TCP': '2',
        'UDP': '3',
        'DCCP': '4',
        'SCTP': '5',
        'ICMP': '1',
        'ICMPv6': '7',
        [this.$t('其他IP协议')]: '6'
      },
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }],
        ports: [{ required: false, validator: validatePorts, trigger: 'blur' }],
        type: [{ required: false, validator: validateType, trigger: 'blur' }],
        v6Type: [{ required: false, validator: validateV6Type, trigger: 'blur' }],
        code: [{ required: false, validator: validateCode, trigger: 'blur' }],
        v6Code: [{ required: false, validator: validateV6Code, trigger: 'blur' }],
        prot: [{ required: false, validator: validateProt, trigger: 'blur' }]
      },
      formLabelWidth: '120px'
    }
  },
  watch: {
    'form.desc': {
      handler (newVal) {
        this.form.desc = newVal.replace(/[\r\n]/g, '')
      },
      immediate: true
    },
    'record.ports': {
      handler (newVal) {
        this.record.ports = newVal.replace(/[\r\n]/g, '')
      },
      immediate: true
    }
  },
  methods: {
    // 发送form表单数据到父组件
    send_form () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let childForm = Object.assign({}, this.form)
          if (childForm.cmd_type === '7') {
            childForm.type = childForm.v6Type
            childForm.code = childForm.v6Code
            delete childForm.v6Type
            delete childForm.v6Code
          }
          this.$emit('childForm', childForm)
        }
      })
    },
    classRef () {
      const data = ['name']
      const textdata = ['desc']
      inputClass(this.$refs, data)
      texttextClass(this.$refs, textdata)
    },
    cmdTypeChange (val) {
      this.$refs.form.clearValidate(['ports', 'type', 'code', 'prot'])
    },
    serviceIcmpv6 (val) {
      getServiceIcmpv6().then(res => {
        this.icmpv6List = res.info
        this.icmpv6ListShow = ['default']
        for (let item in this.icmpv6List) {
          this.icmpv6ListShow.push(item)
        }
      })
    },
    nameChange (data) {
      this.serviceIcmpv6Status = !!this.icmpv6List[data]
      if (this.serviceIcmpv6Status) {
        this.form.v6Type = this.icmpv6List[data].ucType
        this.form.v6Code = this.icmpv6List[data].ucCode
        this.$refs.form.validateField(['v6Code', 'v6Type'])
      } else {
        this.form.v6Type = ''
        this.form.v6Code = ''
        this.$refs.form.clearValidate(['v6Code', 'v6Type'])
      }
    },
    updateView (e) {
      this.$forceUpdate()
    },
    close () {
      this.form = {
        cmd_type: '2',
        pattern: 'default',
        name: '',
        desc: '',
        ports: '',
        type: '',
        v6Type: '',
        code: '',
        v6Code: '',
        prot: ''
      }
      this.icmpv6List = {}
      this.icmpv6ListShow = []
      this.serviceIcmpv6Status = false
      this.$refs.form.resetFields()
    },
    handleKeyCode (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    },
    rulePost (value, zhStr) {
      if (value) {
        if (!String(value).match(zhStr) || (String(value).match(zhStr).length !== String(value).length)) {
          return this.$t('不能输入中文')
        } else if (isNaN(Number(value))) {
          return this.$t('请输入数字')
        } else if (Number(value) > 65535 || Number(value) < 1) {
          return this.$t('端口的范围为1~65535')
        }
      }
      return ''
    }
  }
}
</script>

<style scoped>
.tools_box {
  text-align: left;
}
.circle {
  padding: 5px;
}
</style>
